/**
 * 用户实体类
 * 定义AI侦探应用中的用户数据结构
 */
export class User {
  // 用户ID
  id: string;
  
  // 用户名
  username: string;
  
  // 密码（实际应用中应进行加密存储）
  password: string;
  
  // 真实姓名
  name: string;
  
  // 头像
  avatar: string;
  
  // 邮箱
  email: string;
  
  // 电话号码
  phone: string;
  
  // 用户角色
  role: 'admin' | 'detective' | 'viewer';
  
  // 创建时间
  createdAt: Date;
  
  // 最后登录时间
  lastLoginAt?: Date;
  
  /**
   * 构造函数
   * @param userData 用户数据
   */
  constructor(userData: {
    id?: string;
    username: string;
    password: string;
    name: string;
    avatar: string;
    email: string;
    phone: string;
    role?: 'admin' | 'detective' | 'viewer';
    createdAt?: Date;
    lastLoginAt?: Date;
  }) {
    this.id = userData.id || this.generateId();
    this.username = userData.username;
    this.password = userData.password;
    this.name = userData.name;
    this.avatar = userData.avatar;
    this.email = userData.email;
    this.phone = userData.phone;
    this.role = userData.role || 'detective';
    this.createdAt = userData.createdAt || new Date();
    this.lastLoginAt = userData.lastLoginAt;
  }
  
  /**
   * 生成唯一ID
   * @returns 唯一ID字符串
   */
  private generateId(): string {
    return `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
  
  /**
   * 转换为JSON对象
   * @returns JSON格式的用户数据
   */
  toJSON() {
    return {
      id: this.id,
      username: this.username,
      password: this.password,
      name: this.name,
      avatar: this.avatar,
      email: this.email,
      phone: this.phone,
      role: this.role,
      createdAt: this.createdAt.toISOString(),
      lastLoginAt: this.lastLoginAt?.toISOString()
    };
  }
  
  /**
   * 从JSON对象创建User实例
   * @param json JSON格式的用户数据
   * @returns User实例
   */
  static fromJSON(json: any): User {
    return new User({
      id: json.id,
      username: json.username,
      password: json.password,
      name: json.name,
      avatar: json.avatar,
      email: json.email,
      phone: json.phone,
      role: json.role,
      createdAt: json.createdAt ? new Date(json.createdAt) : new Date(),
      lastLoginAt: json.lastLoginAt ? new Date(json.lastLoginAt) : undefined
    });
  }
}